package com.ylj.contact;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.hjq.toast.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

//https://www.jianshu.com/p/8a31458c4662
public class OkGoUtils {

    /**
     * 网络请求的相关参数
     */
    public static class RequestOption{
        public Context mContext;
        public Map params;
        public String url;
        public AbsPostJsonStringCb iPostJsonStringCb;
        /**
         * 是否同意处理response相应码
         */
        public boolean isNormalDeal = false;
        public JSONObject mJSONObject;
        //public LoadHelpView loadHelpView;


        public RequestOption(Context mContext, String url, Map params, AbsPostJsonStringCb iPostJsonStringCb) {
            this.mContext = mContext;
            this.params = params;
//            String dataStr = "";
//            Iterator iter = params.keySet().iterator();
//            while (iter.hasNext()) {
//                Object key = iter.next();
//                Object value = params.get(key);
//                if(dataStr.length()>0){
//                    dataStr += "&";
//                }
//                dataStr += key+"="+value;
//            }
//            Map mMap = new HashMap();
//            if(dataStr!=null&&dataStr.length()>0){
//                mMap.put("data", RSAUtil.publicEncrypt(dataStr));
//                mMap.put("encrypted", "Y");
//            }
//            this.params = mMap;
            this.url = url;
            this.iPostJsonStringCb = iPostJsonStringCb;
        }
        public RequestOption(Context mContext, String url, Map params, AbsPostJsonStringCb iPostJsonStringCb, boolean isNormalDeal) {
            this.mContext = mContext;
            this.params = params;
//            String dataStr = "";
//            Iterator iter = params.keySet().iterator();
//            while (iter.hasNext()) {
//                Object key = iter.next();
//                Object value = params.get(key);
//                if(dataStr.length()>0){
//                    dataStr += "&";
//                }
//                dataStr += key+"="+value;
//            }
//            Map mMap = new HashMap();
//            mMap.put("data", RSAUtil.publicEncrypt(dataStr));
//            mMap.put("encrypted", "Y");
//            this.params = mMap;
            this.url = url;
            this.iPostJsonStringCb = iPostJsonStringCb;
            this.isNormalDeal = isNormalDeal;
        }
    }


    /**
     * post请求
     */
    public static void postJsonStringCallback(final RequestOption requestOption){
        OkGo.<String>post(requestOption.url)
                .tag(requestOption.mContext)
                .params(requestOption.params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String resp = response.body().toString();
                        if(requestOption.isNormalDeal){
                            if(unifiedProcessingCode(resp, requestOption)){
                                backToSuccessNormal(resp, requestOption);
                            }
                        }else{
                            backToSuccessOriginal(resp, requestOption);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

//                        ToastUtils.show("请求失败，请稍后在试");
                        Log.d("okgoUtil","网络请求异常："+response.toString());

                        if(response.body()!=null){
                            String err = response.body().toString();
                            Log.e("okgoUtil","======= request faile："+requestOption.url+"\n"+"params： "+requestOption.params+"\n"+"response: "+err);
                        }

                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onError(response);
                        }

                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onStart(request);
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onFinish();
                        }
                    }
                });
    }

    public static void postJsonStringCallback(final RequestOption requestOption, String token){
        OkGo.<String>post(requestOption.url)
                .tag(requestOption.mContext).headers("token", token)
                .params(requestOption.params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String resp = response.body().toString();
//                        Log.d("okgoUtil",requestOption.url+"  ======= >>>>>> 请求详情:  "+"\n"+"request："+requestOption.url+"\n"+"params： "+requestOption.params+"\n"+"response: "+resp);

                        // 是否需要 统一的处理
                        if(requestOption.isNormalDeal){
                            if(unifiedProcessingCode(resp, requestOption)){
                                backToSuccessNormal(resp, requestOption);
                            }
                        }else{
                            backToSuccessOriginal(resp, requestOption);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);

//                        ToastUtils.show("请求失败，请稍后在试");
                        Log.d("okgoUtil","网络请求异常："+response.toString());

                        if(response.body()!=null){
                            String err = response.body().toString();
                            Log.e("okgoUtil","======= request faile："+requestOption.url+"\n"+"params： "+requestOption.params+"\n"+"response: "+err);
                        }

                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onError(response);
                        }

                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onStart(request);
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onFinish();
                        }
                    }
                });
    }

    /**
     * 返回码的统一处理
     * 当返回 true 时，代表success。
     * @param resp
     * @param requestOption
     * @return
     */
    private static boolean unifiedProcessingCode(String resp, final RequestOption requestOption) {
        return  false;
    }

    /**
     * 某些错误码的出现，应该让程序直接抛到登录页面
     * @param requestOption
     * @param content
     */
    private static void gotoLogin(final RequestOption requestOption, String content) {
        // code...
    }


    /**
     * get请求
     * @param requestOption
     */
    public  static void getJsonStringCallback(final RequestOption requestOption){
        OkGo.<String>get(requestOption.url)
                // header 参数，如果需要的话
//                .headers("Authorization", "本地存储")
                //.tag()
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String resp = response.body().toString();
                        Log.d("okgoUtil","======= request："+"\n"+requestOption.url+"\n"+"response: "+resp);

                        // 是否需要 统一的处理
                        if(requestOption.isNormalDeal){
                            if(unifiedProcessingCode(resp,requestOption)){
                                backToSuccessNormal(resp, requestOption);
                            }
                        }else{
                            backToSuccessOriginal(resp, requestOption);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.show("请求失败，请稍后在试");
                        if(response.body()!=null){
                            Log.d("okgoUtil","网络请求异常："+response.toString());
                            String err = response.body().toString();
                            Log.d("okgoUtil","======= request faile："+requestOption.url+"\n"+"response: "+err);
                        }

                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onError(response);
                        }

                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onStart(request);
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onFinish();
                        }
                    }
                });
    }

    /**
     * get请求
     * @param requestOption
     */
    public  static void getJsonStringCallback(final RequestOption requestOption, String token){
        OkGo.<String>get(requestOption.url)
                // header 参数，如果需要的话
                .headers("token", token)
                //.tag()
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String resp = response.body().toString();
                        Log.d("okgoUtil","======= request："+"\n"+requestOption.url+"\n"+"response: "+resp);

                        // 是否需要 统一的处理
                        if(requestOption.isNormalDeal){
                            if(unifiedProcessingCode(resp,requestOption)){
                                backToSuccessNormal(resp, requestOption);
                            }
                        }else{
                            backToSuccessOriginal(resp, requestOption);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.show("请求失败，请稍后在试");
                        if(response.body()!=null){
                            Log.d("okgoUtil","网络请求异常："+response.toString());
                            String err = response.body().toString();
                            Log.d("okgoUtil","======= request faile："+requestOption.url+"\n"+"response: "+err);
                        }

                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onError(response);
                        }

                    }

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onStart(request);
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if(requestOption.iPostJsonStringCb !=null){
                            requestOption.iPostJsonStringCb.onFinish();
                        }
                    }
                });
    }

    /**
     * 请求success 通用处理
     * @param resp
     * @param requestOption
     */
    private static void backToSuccessNormal(String resp, RequestOption requestOption) {

        if(requestOption.iPostJsonStringCb !=null){
            try {
                JSONObject jsonObject = new JSONObject(resp);
                String data = jsonObject.getString("data");
                requestOption.iPostJsonStringCb.onSuccess(resp,data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 请求成功，原生字符串处理
     * @param resp
     * @param requestOption
     */
    private static void backToSuccessOriginal(String resp, RequestOption requestOption) {

        if(requestOption.iPostJsonStringCb !=null){
            requestOption.iPostJsonStringCb.onSuccess(resp,resp);
        }
    }

    public void cancel(Context mContext){
        OkGo.cancelTag(OkGo.getInstance().getOkHttpClient(), mContext);
    }

    public interface IPostJsonStringCb {
        void onSuccess(String str, String data);
        void onError(Response<String> response);
        void onStart(Request<String, ? extends Request> str);
        void onFinish();
    }
}
